import { IEchartsData } from '@/model/echarts/echartsInter'
import { categoryData, dataFlag, markPoint, nameLength, noSeries } from '@/utils/echartsCommonFun'
import { BarSeriesOption, EChartsOption, GridOption, TooltipOption, YAXisOption } from 'echarts/types/dist/shared'
import { BarItemStyleOption } from 'echarts/types/src/chart/bar/BarSeries'

export function Chart (datas:IEchartsData) {
  const series = []
  let category:Array<string> = []
  let max = 0
  const flag = dataFlag(datas.data)
  if (flag > 0 && flag === datas.data.length) { // 没有数据
    series.push(noSeries())
  } else {
    datas.data.forEach((data, index) => {
      let value:Array<{name:string, value:number}> = []
      if (data.value) {
        value = data.value
        value.forEach(item => {
          category = categoryData(category, item.name)
          max = nameLength(max, item.name)
        })
      }
      if (index === datas.data.length - 1) {
        series.push({
          name: data.name ? data.name : '',
          type: 'bar',
          data: value,
          stack: 'stack',
          barWidth: '20%',
          smooth: true,
          symbol: 'none',
          itemStyle: {
            borderRadius: [0, 20, 20, 0]
          } as BarItemStyleOption,
          markPoint: markPoint(data),
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        } as BarSeriesOption)
      } else {
        series.push({
          name: data.name ? data.name : '',
          type: 'bar',
          data: value,
          stack: 'stack',
          barWidth: '20%',
          barMaxWidth: 15,
          barMinWidth: 1,
          smooth: true,
          symbol: 'none',
          markPoint: markPoint(data),
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        } as BarSeriesOption)
      }
    })
  }
  return {
    color: ['#CD163F', '#0082B3'],
    xAxis: xAxis(),
    yAxis: yAxis(category, true),
    grid: grid(),
    tooltip: tooltip(),
    series: series
  } as EChartsOption
}

function xAxis () {
  return {
    axisLine: {
      show: true
    },
    axisTick: {
      show: true
    }
  }
}

function yAxis (data:Array<string>, boundaryGap?: boolean | Array<string>) {
  return {
    data: data,
    type: 'category',
    boundaryGap: boundaryGap || false,
    axisTick: {
      show: false
    }
  } as YAXisOption
}

function grid () {
  return {
    left: 0,
    right: 15,
    top: 20,
    bottom: 0,
    containLabel: true
  } as GridOption
}

function tooltip () {
  return {
    trigger: 'axis',
    confine: true,
    axisPointer: {
      textStyle: {
        color: '#fff'
      }
    }
  } as TooltipOption
}
